package cn.zhentao.controller;

import cn.zhentao.config.MinioConfig;
import cn.zhentao.config.MinioUtils;
import cn.zhentao.mapper.TbMinioMapper;
import cn.zhentao.pojo.TbMinio;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class MinioController {
    @Autowired
    private MinioUtils minioClientUtils;
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private TbMinioMapper tbMinioMapper;

    @PostMapping("upload")
    public Map<String, String> uploadFile(MultipartFile file) {
        Map<String, String> map = new HashMap<>();
        //获取文件源文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件扩展名
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成逻辑文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String logicFileName = uuid + extName;
        String bucketName = minioConfig.getBucketName();
        String fileUrl = minioConfig.getEndpoint() + "/" + bucketName + "/" + logicFileName;
        try {
            minioClientUtils.putObject(bucketName, file, logicFileName);

            //保存到数据库
            TbMinio minio = new TbMinio();

            minio.setId(uuid);
            minio.setPath(fileUrl);
            minio.setTitle(originalFilename);
            tbMinioMapper.insert(minio);

            map.put("filename", fileUrl);
            map.put("status", "success");
            map.put("message", "文件上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", "error");
            map.put("message", "文件上传失败: " + e.getMessage());
            throw new RuntimeException("文件上传失败", e); // 触发事务回滚
        }
        System.out.println(map);
        return map;
    }

    @RequestMapping("findMinio")
    public List<TbMinio> findMinio(){
        QueryWrapper<TbMinio> queryWrapper = new QueryWrapper<>();
        return tbMinioMapper.selectList(queryWrapper);
    }
}
